const express = require('express');

const morgan = require('morgan');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xssClean = require('xss-clean');
const AppError = require('./utils/appError');
const globalErrorhandler = require('./controller/errController');
const tourRouter = require('./routes/tourRoute');
const userRouter = require('./routes/usersRoute');
const reviewRouter = require('./routes/reviewRoute');
const app = express();
// 1) 全局中间件
// 设置安全的http头
app.use(helmet());
if (process.env.NODE_ENV === 'development') {
    app.use(morgan('dev'));
}

const limiter = rateLimit({
    max:100,
    windowMs:60 * 60 *1000,
    message: 'Too many requests from this Ip 一小时后再来'
})

// 限制请求来自同样的I
app.use('/api', limiter);



// 解析body  从req的body中解析
app.use(express.json({limit:'10kb'}));

// nosql查询注入 以及数据清理
app.use(mongoSanitize())
// 防止xss跨站攻击
app.use(xssClean());
// 服务器静态文件
app.use(express.static(`${__dirname}/public`));

app.use((req, res, next) => {
    console.log('hellp from the middleware');
    next();
})
app.use((req, res, next) => {
    req.requestTime = new Date().toISOString();
    next();
})


// 3）routers

app.use('/api/v1/tours', tourRouter);
app.use('/api/v1/users', userRouter);
app.use('/api/v1/reviews', reviewRouter);
app.all('*',(req,res,next)=>{
    // res.status(404).json({
    //     status:"fail",
    //     message:'404 not found'
    // })
    // const err = new Error(`Cant find ${req.originalUrl} on this server`);
    // err.status = 'fail';
    // err.statusCode = 404;
    next(new AppError(`Cant find ${req.originalUrl} on this server`,404));
})

app.use(globalErrorhandler);
module.exports = app